<template>
  <div class="simulator-container">
    <!-- 顶部工具栏 -->
    <header class="simulator-header">
      <div class="header-left">
        <el-button @click="goBack" type="primary" plain>
          <el-icon><ArrowLeft /></el-icon>
          返回设备列表
        </el-button>
        <div class="device-info">
          <h2>{{ currentDevice?.name || '设备模拟' }}</h2>
          <el-tag size="small" type="success">模拟模式</el-tag>
        </div>
      </div>
      <div class="header-right">
        <el-button-group>
          <el-button @click="resetSimulation">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
          <el-button @click="toggleFullscreen">
            <el-icon><FullScreen /></el-icon>
            全屏
          </el-button>
        </el-button-group>
      </div>
    </header>

    <!-- 主要模拟区域 -->
    <main class="simulator-main">
      <div class="simulation-workspace">
        <!-- 设备界面显示区域 -->
        <div class="device-screen" ref="deviceScreenRef">
          <div v-if="currentImage" class="image-container">
            <CoordinateOverlay
              :image-url="currentImage.url"
              :image-name="currentImage.name"
              :clickable-areas="clickableAreas"
              :coordinate-file="currentDevice?.coordinateLog"
              :editable="editMode"
              @area-click="handleAreaClick"
              @coordinates-updated="handleCoordinatesUpdate"
              @image-loaded="handleImageLoad"
              @image-error="handleImageError"
            />
          </div>
          
          <!-- 空状态 -->
          <div v-else class="empty-screen">
            <el-icon size="64"><Monitor /></el-icon>
            <h3>暂无界面图片</h3>
            <p>请先上传设备界面图片</p>
          </div>
        </div>

        <!-- 侧边控制面板 -->
        <aside class="control-panel">
          <div class="panel-section">
            <h3>界面导航</h3>
            <div class="image-list">
              <div
                v-for="(image, index) in deviceImages"
                :key="image.id"
                class="image-item"
                :class="{ active: currentImage?.id === image.id }"
                @click="switchToImage(image)"
              >
                <img :src="image.thumbnail || image.url" :alt="image.name" />
                <span class="image-name">{{ image.name }}</span>
              </div>
            </div>
          </div>

          <div class="panel-section">
            <h3>操作历史</h3>
            <div class="history-list">
              <div
                v-for="(record, index) in operationHistory"
                :key="index"
                class="history-item"
              >
                <div class="history-time">
                  {{ formatTime(record.timestamp) }}
                </div>
                <div class="history-action">
                  {{ record.action }}
                </div>
              </div>
              <div v-if="operationHistory.length === 0" class="empty-history">
                暂无操作记录
              </div>
            </div>
          </div>

          <div class="panel-section">
            <h3>模式控制</h3>
            <div class="mode-controls">
              <el-switch
                v-model="editMode"
                active-text="编辑模式"
                inactive-text="演示模式"
                @change="handleModeChange"
              />
              <el-button 
                v-if="editMode" 
                size="small" 
                type="primary"
                @click="saveCoordinates"
              >
                保存坐标
              </el-button>
            </div>
          </div>

          <div class="panel-section">
            <h3>调试信息</h3>
            <div class="debug-info">
              <div class="debug-item">
                <label>当前坐标:</label>
                <span>{{ cursorPosition ? `(${cursorPosition.x}, ${cursorPosition.y})` : '未检测' }}</span>
              </div>
              <div class="debug-item">
                <label>可点击区域:</label>
                <span>{{ clickableAreas.length }} 个</span>
              </div>
              <div class="debug-item">
                <label>图片尺寸:</label>
                <span>{{ imageSize ? `${imageSize.width}x${imageSize.height}` : '未加载' }}</span>
              </div>
              <div class="debug-item">
                <label>当前模式:</label>
                <span>{{ editMode ? '编辑模式' : '演示模式' }}</span>
              </div>
            </div>
          </div>
        </aside>
      </div>
    </main>
  </div>
</template>

<script setup>
/**
 * 设备模拟器组件
 * 
 * 核心功能：
 * - 设备界面图片展示
 * - 可点击区域识别和交互
 * - 鼠标位置检测和匹配
 * - 界面跳转模拟
 * - 操作历史记录
 */

import { ref, computed, onMounted, onUnmounted, nextTick } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { useDeviceStore } from '@/stores/device'
import { mockClickableAreas } from '@/mock/devices'
import * as deviceApi from '@/api/device'
import CoordinateOverlay from '@/components/CoordinateOverlay.vue'

console.log('Simulator组件加载')

const route = useRoute()
const router = useRouter()
const deviceStore = useDeviceStore()

// 响应式数据
const deviceScreenRef = ref()
const currentImage = ref(null)
const deviceImages = ref([])
const clickableAreas = ref([])
const cursorPosition = ref(null)
const imageSize = ref(null)
const operationHistory = ref([])
const isFullscreen = ref(false)
const editMode = ref(false)

// 计算属性
const currentDevice = computed(() => deviceStore.currentDevice)
const deviceId = computed(() => route.params.deviceId)

// 方法定义
const goBack = () => {
  console.log('返回设备列表')
  router.push('/')
}

const resetSimulation = () => {
  console.log('重置模拟状态')
  operationHistory.value = []
  cursorPosition.value = null
  if (deviceImages.value.length > 0) {
    switchToImage(deviceImages.value[0])
  }
  ElMessage.success('模拟状态已重置')
}

const toggleFullscreen = () => {
  console.log('切换全屏模式')
  if (!document.fullscreenElement) {
    deviceScreenRef.value?.requestFullscreen()
    isFullscreen.value = true
  } else {
    document.exitFullscreen()
    isFullscreen.value = false
  }
}

const handleImageLoad = (imageInfo) => {
  console.log('设备图片加载完成')
  if (imageInfo) {
    imageSize.value = imageInfo.originalSize
    console.log('图片尺寸:', imageSize.value)
  }
}

const handleImageError = (imageUrl) => {
  console.error('图片加载失败:', imageUrl)
  ElMessage.error('图片加载失败')
}


const handleAreaClick = async (area) => {
  console.log('点击可点击区域:', area.label)
  
  if (editMode.value) {
    // 编辑模式下不执行跳转，只记录操作
    addOperationRecord(`编辑模式 - 选择区域: ${area.label}`)
    return
  }
  
  try {
    // 模拟模式下处理点击事件
    if (area.nextImage) {
      const nextImage = deviceImages.value.find(img => img.id === area.nextImage)
      if (nextImage) {
        switchToImage(nextImage)
        addOperationRecord(`点击"${area.label}" -> 跳转到"${nextImage.name}"`)
        ElMessage.success(`跳转到: ${nextImage.name}`)
      } else {
        addOperationRecord(`点击"${area.label}" - 目标界面不存在`)
        ElMessage.warning('目标界面不存在')
      }
    } else {
      addOperationRecord(`点击"${area.label}" - 执行操作`)
      ElMessage.success(`操作成功: ${area.label}`)
    }
  } catch (error) {
    console.error('处理点击事件失败:', error)
    addOperationRecord(`点击"${area.label}" - 操作失败`)
    ElMessage.error('操作失败')
  }
}

const switchToImage = (image) => {
  console.log('切换到图片:', image.name)
  currentImage.value = image
  loadClickableAreas(image.id)
  addOperationRecord(`切换到界面: ${image.name}`)
}

const loadClickableAreas = async (imageId) => {
  try {
    console.log('加载可点击区域:', imageId)
    // 使用模拟数据
    clickableAreas.value = mockClickableAreas[imageId] || []
    console.log(`加载了${clickableAreas.value.length}个可点击区域`)
  } catch (error) {
    console.error('加载可点击区域失败:', error)
    clickableAreas.value = []
  }
}


const addOperationRecord = (action) => {
  operationHistory.value.unshift({
    timestamp: new Date(),
    action: action
  })
  
  // 限制历史记录数量
  if (operationHistory.value.length > 50) {
    operationHistory.value = operationHistory.value.slice(0, 50)
  }
}

const formatTime = (timestamp) => {
  return timestamp.toLocaleTimeString()
}

// 新增方法
const handleModeChange = (value) => {
  console.log('模式切换:', value ? '编辑模式' : '演示模式')
  addOperationRecord(`切换到${value ? '编辑' : '演示'}模式`)
  ElMessage.info(`已切换到${value ? '编辑' : '演示'}模式`)
}

const handleCoordinatesUpdate = (coordinates) => {
  console.log('坐标数据更新:', coordinates)
  clickableAreas.value = coordinates
  addOperationRecord('坐标数据已更新')
}

const saveCoordinates = async () => {
  try {
    console.log('保存坐标数据')
    // TODO: 调用后端API保存坐标数据
    const coordinateData = {
      imageId: currentImage.value.id,
      areas: clickableAreas.value
    }
    
    // 模拟保存成功
    addOperationRecord('坐标数据保存成功')
    ElMessage.success('坐标数据保存成功')
  } catch (error) {
    console.error('保存坐标数据失败:', error)
    ElMessage.error('保存坐标数据失败')
  }
}

const loadDeviceData = async () => {
  try {
    console.log('加载设备数据:', deviceId.value)
    
    // 获取设备详情
    const deviceResponse = await deviceApi.getDevice(deviceId.value)
    const device = deviceResponse.data
    deviceStore.setCurrentDevice(device)
    
    // 获取设备图片列表
    deviceImages.value = device.images || []
    
    // 设置默认显示第一张图片
    if (deviceImages.value.length > 0) {
      switchToImage(deviceImages.value[0])
    }
    
    console.log(`设备数据加载完成，共${deviceImages.value.length}张图片`)
  } catch (error) {
    console.error('加载设备数据失败:', error)
    ElMessage.error('加载设备数据失败')
  }
}

// 全屏状态监听
const handleFullscreenChange = () => {
  isFullscreen.value = !!document.fullscreenElement
}

// 生命周期
onMounted(async () => {
  console.log('Simulator页面挂载，设备ID:', deviceId.value)
  await loadDeviceData()
  
  // 监听全屏状态变化
  document.addEventListener('fullscreenchange', handleFullscreenChange)
})

onUnmounted(() => {
  document.removeEventListener('fullscreenchange', handleFullscreenChange)
})
</script>

<style scoped>
.simulator-container {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background: #1a1a1a;
  color: #ffffff;
}

.simulator-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 24px;
  background: rgba(255, 255, 255, 0.1);
  backdrop-filter: blur(10px);
  border-bottom: 1px solid rgba(255, 255, 255, 0.1);
}

.header-left {
  display: flex;
  align-items: center;
  gap: 16px;
}

.device-info h2 {
  margin: 0 0 4px 0;
  font-size: 18px;
  font-weight: 600;
}

.simulator-main {
  flex: 1;
  overflow: hidden;
}

.simulation-workspace {
  display: flex;
  height: 100%;
}

.device-screen {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #000;
  position: relative;
}

.image-container {
  position: relative;
  max-width: 100%;
  max-height: 100%;
}


.empty-screen {
  text-align: center;
  color: #909399;
}

.empty-screen h3 {
  margin: 16px 0 8px 0;
  font-size: 18px;
}

.control-panel {
  width: 300px;
  background: rgba(255, 255, 255, 0.05);
  backdrop-filter: blur(10px);
  border-left: 1px solid rgba(255, 255, 255, 0.1);
  overflow-y: auto;
}

.panel-section {
  padding: 20px;
  border-bottom: 1px solid rgba(255, 255, 255, 0.1);
}

.panel-section h3 {
  margin: 0 0 16px 0;
  font-size: 16px;
  font-weight: 600;
  color: #409eff;
}

.mode-controls {
  display: flex;
  flex-direction: column;
  gap: 12px;
  align-items: flex-start;
}

.mode-controls .el-switch {
  margin-bottom: 8px;
}

.image-list {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.image-item {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 8px;
  border-radius: 6px;
  cursor: pointer;
  transition: background-color 0.3s ease;
}

.image-item:hover {
  background: rgba(255, 255, 255, 0.1);
}

.image-item.active {
  background: rgba(64, 158, 255, 0.2);
  border: 1px solid #409eff;
}

.image-item img {
  width: 40px;
  height: 40px;
  object-fit: cover;
  border-radius: 4px;
}

.image-name {
  font-size: 14px;
  flex: 1;
}

.history-list {
  max-height: 200px;
  overflow-y: auto;
}

.history-item {
  padding: 8px 0;
  border-bottom: 1px solid rgba(255, 255, 255, 0.05);
}

.history-time {
  font-size: 12px;
  color: #909399;
  margin-bottom: 4px;
}

.history-action {
  font-size: 14px;
}

.empty-history {
  text-align: center;
  color: #909399;
  font-size: 14px;
  padding: 20px 0;
}

.debug-info {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.debug-item {
  display: flex;
  justify-content: space-between;
  font-size: 14px;
}

.debug-item label {
  color: #909399;
}
</style>

